package com.sl.test;

import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * spring的单元测试基类，完成了对配置文件和容器的初始化加载
 */
@RunWith(BlockJUnit4ClassRunner.class)
public class UnitTestBase {
    private String springXmlPath;
    private ClassPathXmlApplicationContext context;

    public UnitTestBase() {
    }



    public UnitTestBase(String springXmlPath) {
        this.springXmlPath = springXmlPath;
    }

    //初始化容器
    @Before
    public void before() {
        if (springXmlPath.isEmpty()) {
            this.springXmlPath = "classpath*:spring-*.xml";
        }
        try {
            context = new ClassPathXmlApplicationContext(springXmlPath);
            context.start();
        } catch (BeansException e) {
            e.printStackTrace();
        }
    }

    @After
    public void after() {
        if (context != null) {
            context.destroy();
        }
    }

    protected <T extends Object> T getBean(String beanId) {
        try {
            return (T)context.getBean(beanId);
        } catch (BeansException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected <T extends Object> T getBean(Class<T> clazz) {
        try {
            return context.getBean(clazz);
        } catch (BeansException e) {
            e.printStackTrace();
            return null;
        }
    }
}